<script>
	import LoginUtil from '@/main/common/LoginUtil.js'
	import constant from '@/common/constant.js'
	
	import TencentCloudChat from '@tencentcloud/chat';
	import { TUIChatKit, genTestUserSig } from "./TUIKit";
	import { TUILogin } from "@tencentcloud/tui-core";
	import IMUtil from '@/main/common/IMUtil.js';
	
	// IMUtil.init()
	uni.$chat_SDKAppID = constant.imApppId;
	uni.$chat_secretKey = constant.imSecretKey;
	uni.$TUIKit = TencentCloudChat.create({
		SDKAppID: uni.$chat_SDKAppID
	});
	//离线推送
	// uni.$TUIOfflinePush = uni.requireNativePlugin("TencentCloud-TUIOfflinePush");
	// console.warn(uni.$TUIOfflinePush, "TUIOfflinePush ｜ ok");
	

	export default {
		globalData: {
			webUrl: '',
			webTitle: '',
			chatUserId: '',
			chatTxCode: '',
			openTicketMin: false,
			ticketStartTime: 0,
			ticketTotalTime: 180,
			deviceModel: '',
			versionName: '',
		},
		onLaunch: function() {
			uni.$online = constant.online;
			uni.getSystemInfo({
				success: (e) => {
					this.globalData.deviceModel = e.brand + '/' + e.deviceModel;
				}
			})
			// #ifdef APP-PLUS
			plus.runtime.getProperty(plus.runtime.appid, (info) => {
				this.versionName = info.version;
				this.globalData.versionName = info.version;
			});
			// #endif
			this.checkUpdate();
			this.isLogin();
			this.loginIM();
		},

		methods: {
			isLogin() {
				const login = uni.getStorageSync("login");
				if (!login) {
					LoginUtil.loginOnce()
				}
			},
			loginIM() {
				const txCode = uni.getStorageSync("userTxCode");
				const token = uni.getStorageSync("token");
				if (txCode && token) {
					uni.$chat_userID = txCode + '';
					const config = {
						userID: uni.$chat_userID,
						SDKAppID: uni.$chat_SDKAppID,
						secretKey: uni.$chat_secretKey,
					}
					uni.$chat_userSig = genTestUserSig(config).userSig;
					TUIChatKit.init();
				
					const options = {
						SDKAppID: uni.$chat_SDKAppID,
						userID: uni.$chat_userID,
						userSig: uni.$chat_userSig,
						useUploadPlugin: true,
						framework: `vue2`,
					};
					//IM登录
					TUILogin.login(options).then(res => {
						console.log("IM登录成功：" + JSON.stringify(res));
						this.initUnReadMessage();
					}).catch(error => {
						console.log('IM登录失败:' + JSON.stringify(error));
					});
				}
			},
			initUnReadMessage() {
				//初始化未读消息
				setTimeout(()=>{
					uni.$TUIKit.getConversationList().then(res => {
						const unReadMessageCount = uni.$TUIKit.getTotalUnreadMessageCount();
						this.setUnReadMessageCount(unReadMessageCount);
					}).catch(error => {});
				}, 1000)
				
				//监听未读消息数
				uni.$TUIKit.on(TencentCloudChat.EVENT.TOTAL_UNREAD_MESSAGE_COUNT_UPDATED, event => {
					this.setUnReadMessageCount(event.data);
				});
			},
			setUnReadMessageCount(count) {
				if (count > 0) {
					uni.setTabBarBadge({
						index: constant.messageIndex,
						text: '' + count
					})
				} else {
					uni.removeTabBarBadge({
						index: constant.messageIndex
					})
				}
			},
			

			//检查更新
			checkUpdate() {
				// #ifdef APP-PLUS
				let urlstr = "https://zhiyuapp.oss-cn-fuzhou.aliyuncs.com/uniapp_android/poposeConfig-hw.json?t=" + new Date().getTime();
				uni.request({
					url: urlstr,
					success: (res) => {
						uni.setStorageSync('vipManage', res.data.vipManage);
						uni.setStorageSync('ticketPrice', res.data.ticketPrice);
						uni.setStorageSync('isaliPay', res.data.isaliPay);
						uni.setStorageSync('isWxpay', res.data.isWxpay);
						uni.setStorageSync('wxappid', res.data.wxappid);
						uni.setStorageSync('secret', res.data.secret);
						uni.setStorageSync('xiaochengpay', res.data.xiaochengpay);
						if (res.data.ticketTime) {
							this.globalData.ticketTotalTime = res.data.ticketTime
						}
						console.log('线上版本: ',res.data.vss);
						console.log('本地版本: ',this.versionName);
						if (res.data.open == "1" && res.data.vss != this.versionName) {
							this.install(res.data.wgtUrl);
						}
					}
				})
				// #endif
			},

			//wgt下载安装
			install(wgtUrl) {
				// #ifdef APP-PLUS
				plus.downloader.createDownload(wgtUrl, {
					filename: "_doc/update/"
				}, (d, status) => {
					if (status == 200) {
						plus.runtime.install(d.filename, {
							force: true
						}, function() {
							plus.nativeUI.closeWaiting();
							plus.runtime.restart();
						}, function(e) {
							plus.nativeUI.closeWaiting();
						});
					} else {
						plus.nativeUI.closeWaiting();
					}
				}).start();
				// #endif
			},

			toTicket() {
				if (0 == this.globalData.ticketStartTime) {
					let timeId = setInterval(() => {
						console.log('ticket--start', this.globalData.ticketStartTime);
						this.globalData.ticketStartTime++
						if (this.globalData.ticketStartTime == this.globalData.ticketTotalTime) {
							clearInterval(timeId)
							uni.setStorageSync("ticketOver" + uni.getStorageSync('userId'), true)
							this.globalData.ticketStartTime = 0
							this.globalData.openTicketMin = true
							if(!uni.getStorageSync('vip')){
								uni.reLaunch({
									url: '/pages/tab/home/home',
								});
							}
						}
					}, 1000)
				}
			}

		}
	}
</script>

<style lang="scss">
	page {
		background-color: #f5f5f5;
	}
</style>